package cn.hfatec.shms.system.upload.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.system.upload.service.UploadService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author: panwb
 *
 * Date: 2015/11/24
 * Time: 9:11
 */
@Controller
@RequestMapping("/upload")
public class UploadAction {

    private Logger logger = LoggerFactory.getLogger(UploadAction.class);

    @Resource(name = "UploadService")
    private UploadService uploadService;

    @Resource(name = "shmsProperties")
    private ShmsProperties shmsProperties;

    /**
     *
     * ajax异步上传文件
     *
     * @param file
     * @param fileType
     * @param request
     * @return
     */
    @RequestMapping("/ajax")
    @ResponseBody
    public String uploadFile(MultipartFile file,String fileType, HttpServletRequest request) {

        try {
            return uploadService.uploadFile(file,fileType, request);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new JsonResponse(JsonResponse.RETURN_FAILURE, "文件上传异常").toString();
        }
    }

    /**
     *
     * 根据路径获取图片信息
     *
     */
    @RequestMapping("/**")
    public void getImageFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            String url = request.getRequestURI();
            String filePath = url.substring(url.indexOf("/upload") + 7);
            OutputStream outputStream = response.getOutputStream();
            String uploadPath = shmsProperties.getUploadPath();
            File imgFile = new File(uploadPath + File.separator + filePath);
            if(imgFile.exists() && imgFile.isFile()) {
                InputStream inputStream = new FileInputStream(imgFile);
                IOUtils.copy(inputStream, outputStream);
                IOUtils.closeQuietly(inputStream);
            }
            outputStream.flush();
            IOUtils.closeQuietly(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
